import Ranking from "./Ranking.js";
import { Data } from "#fansky";

async function readData(uid) {
    return await Data.readJSON(`data/PlayerData/gs/${uid}.json`, 'root')
}

async function getData(e, uid) {
    let data = await readData(uid)
    if (!data) {
        return e.reply(`uid: ${uid} 无本地数据~`)
    }
    let { stats } = data.info
    if (!stats || !Object.keys(stats).length > 0) {
        return e.reply("数据为空, 请先[ #角色 ]....", true)
    }
    let result
    if (!e.box) {
        result = {
            "achievement_number": stats.achievement,
            "total_index": "本地数据",
            "title": "本地数据",
            "grade": "本地数据"
        }
    } else {
        let { luxuriousChest, preciousChest, exquisiteChest, commonChest } = stats
        let totalChest = luxuriousChest + preciousChest + exquisiteChest + commonChest
        let box = luxuriousChest * 10 + preciousChest * 5 + exquisiteChest * 2 + commonChest * 1
        let calcBegin = await Q_calc(luxuriousChest, preciousChest, exquisiteChest, commonChest)
        let score = calculateY3(calcBegin)
        result = {
            box,
            total_index: "本地数据",
            title: "本地数据",
            total_box: totalChest,
            grade: score,
            luxurious: luxuriousChest,
            precious: preciousChest,
            exquisite: exquisiteChest,
            common: commonChest
        }
    }
    return await Ranking.renderData(e, uid, result)
}

async function checkData(uid, data) {
    let localData = await readData(uid)
    if (data.achievement_number < localData.info.stats.achievement) {
        data.total_index = data.total_index + `(${data.achievement_number})`
        data.achievement_number = localData.info.stats.achievement
    }
    return data
}

async function Q_calc(f, g, h, i) {
    let l = 0.9028, m = 0.0683, n = 0.0208, o = 0.0081;
    // 获取各宝箱总数
    let { luxurious_chest, precious_chest, exquisite_chest, common_chest } = await Ranking.getAchievement();
    return ((f / luxurious_chest) * l) + ((g / precious_chest) * m) + ((h / exquisite_chest) * n) + ((i / common_chest) * o);
}

function calculateY3(m) {
    const coefficients = [ 138691.296704388, -1339947.56772589, 5389544.47894393, -11353458.0517414, 12115264.4925049, -2266146.54178447, -10540289.0388717, 13994887.1972744, -8293415.19130523, 2433926.22137088, -278957.333386943 ];
    let result = 0;
    for (let i = 0; i < coefficients.length; i++) {
        result += coefficients[i] * Math.pow(m, i);
    }
    return result.toFixed(3);
}

export { getData, checkData }
